package com.zmj.framework.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.springframework.jdbc.core.RowMapper;

public class InsertSqlRowMapper implements RowMapper {
	private String tableName;

	public InsertSqlRowMapper(String tableName) {
		this.tableName = tableName;
	}

	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		Object t = null;

		StringBuffer bufferFields = new StringBuffer(100);
		StringBuffer bufferValues = new StringBuffer(100);
		StringBuffer bufferSQL = new StringBuffer(300);
		String backSql = "";
		ResultSetMetaData rmd = rs.getMetaData();

		for (int i = 1; i <= rmd.getColumnCount(); ++i) {
			String typeName = rmd.getColumnTypeName(i);
			if (typeName.equals("DATE")) {
				Timestamp d = rs.getTimestamp(i);
				if (d != null) {
					bufferFields.append(rmd.getColumnName(i));
					bufferFields.append(",");
					bufferValues.append("to_Date('");
					if (d.toString().length() > 19)
						bufferValues.append(d.toString().substring(0, 19));
					else {
						bufferValues.append(d.toString());
					}
					bufferValues.append("','yyyy-mm-dd HH24:MI:SS')");
					bufferValues.append(",");
				}
			} else if (typeName.equals("NUMBER")) {
				double d = rs.getDouble(i);
				bufferFields.append(rmd.getColumnName(i));
				bufferFields.append(",");
				bufferValues.append(d);
				bufferValues.append(",");
			} else {
				String s = rs.getString(i);
				if (s != null) {
					bufferFields.append(rmd.getColumnName(i));
					bufferFields.append(",");
					bufferValues.append("'");
					bufferValues.append(s.trim());
					bufferValues.append("',");
				}
			}
		}

		bufferSQL.append("insert into ");
		bufferSQL.append(this.tableName);
		bufferSQL.append(" (");
		bufferSQL.append(bufferFields.substring(0, bufferFields.length() - 1));

		bufferSQL.append(") values (");
		bufferSQL.append(bufferValues.substring(0, bufferValues.length() - 1));

		bufferSQL.append(")");

		backSql = bufferSQL.toString();

		bufferFields.setLength(0);
		bufferValues.setLength(0);
		bufferSQL.setLength(0);

		return backSql;
	}
}